<template>
  <div class="login-container">
    <!-- 头部 NavBar -->
    <van-nav-bar title="黑马头条-登录">
      <template #left>
        <img class="logo" src="@/assets/images/logo.png" alt="" />
      </template>
    </van-nav-bar>
    <!-- Form 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        name="mobile"
        type="tel"
        label="手机号码"
        placeholder="手机号"
        required
        :rules="[rules.tel]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        name="code"
        label="用户密码"
        placeholder="密码"
        required
        :rules="[rules.code]"
      />
      <div style="margin: 16px">
        <van-button
        round
        block
        :loading=isloading
        :disabled=isloading
        loading-text="加载中..."
        type="info"
        native-type="submit">
          登录
          </van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { Notify } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      isloading: false, // 登录的加载状态
      formLogin: {
        mobile: '15075099159',
        code: '246810' // 默认只能用246810后台规定了
      },
      //   校验规则
      rules: {
        tel: {
          required: true,
          message: '请填写正确的手机号',
          trigger: 'onChange',
          pattern: /^1[3456789]\d{9}$/
        },
        code: {
          required: true,
          message: '请填写正确的验证码',
          trigger: 'onChange',
          pattern: /^\d{6}$/
        }

      }
    }
  },
  methods: {
    ...mapActions(['asyncLoginAction']),
    async onSubmit () {
      this.isloading = true
      try {
        //   await 把异步代码 转为 同步代码  必须成双成对  async await 出现
        await this.asyncLoginAction(this.formLogin)
        Notify({ type: 'success', message: '登录成功' })
        this.$router.replace({
          // this.$route.query.from
          // 登陆成功，如果有from表示从这个路径调过来，那么就要让登录之后去到这个地址，否则就去首页
          path: this.$route.query.from || '/layout'
        })
      } catch (err) {
        Notify({ type: 'warnning', message: '验证码错误' })
      } finally {
        this.isloading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
// .van-nav-bar {
//   background: #007bff;
// }
// /* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
// /deep/ .van-nav-bar__title {
//   color: white;
// }
</style>
